package com.party.controller.sys.learning;

import com.party.common.Page;
import com.party.common.Tools;
import com.party.model.Curriculum;
import com.party.model.Exam;
import com.party.model.SysUser;
import com.party.model.User2Curriculum;
import com.party.service.study.CurriculumService;
import com.party.service.study.User2curriculumService;
import com.party.service.sys.SysUserService;
import org.aspectj.apache.bcel.classfile.InnerClass;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by 011926 on 2014/9/14.
 */
@Controller
@RequestMapping("/sys/curriculum")
public class CurriculumController
{
    @Resource
    CurriculumService curriculumService;
    @Resource
    SysUserService sysUserService;
    @Resource
    User2curriculumService user2curriculumService;
    private int pageSize = 9;

    /**
     *  列表
     * @param request
     * @param response
     * @return
     */
    @RequestMapping(value = "/index", method = RequestMethod.GET)
    public ModelAndView index(
            HttpServletRequest request,
            HttpServletResponse response
    ) {

        ModelAndView modelAndView = new ModelAndView();
        modelAndView.setViewName("/sys/learning/curriculum");
        return modelAndView;
    }

    @RequestMapping(value = "/query")
    @ResponseBody
    public Map<String,Object> query(HttpServletRequest req) {
        Map<String, Object> map = new HashMap<String, Object>();
        String pageIndexStr = req.getParameter("pageIndex");
        String title = req.getParameter("title");
        String content = req.getParameter("content");

        int pageIndex = 1;
        if (pageIndexStr != null && !"".equals(pageIndexStr)) {
            pageIndex = Integer.parseInt(pageIndexStr);
        }
        Curriculum curriculum = new Curriculum();
        curriculum.setContent(content);
        curriculum.setTitle(title);
        Page p = this.curriculumService.getList(curriculum, pageSize, pageIndex);

        map.put("pageCount",p.getTotalPageCount() );
        map.put("tableData", p.getResult());
        return map;
    }

    @RequestMapping(value = "/delete")
    @ResponseBody
    public Map<String,Object> delete(HttpServletRequest req) {
        String ids = req.getParameter("ids");
        int num = 0;
        if(ids != null && !"".equals(ids))
        {
            String[] idStrs = ids.split(",");
            if(idStrs.length>0)
            {
                for(String id : idStrs)
                {
                    if(Tools.isNumber(id))
                    {
                        num = num+this.curriculumService.delete(Integer.parseInt(id));
                    }
                }
            }

        }
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("num",num);
        return map;
    }


    /**
     * 增加
     * @return
     */
    @RequestMapping(value = "/add")
    public ModelAndView add() {
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.setViewName("/sys/learning/curriculum_add");
        return modelAndView;
    }

    /**
     * 增加数据
     * @return
     */
    @RequestMapping(value = "/addData")
    @ResponseBody
    public Map<String,Object> addData(
            @ModelAttribute("curriculum") Curriculum curriculum,
            HttpSession session,
            HttpServletRequest request,
            HttpServletResponse response) {

        String status="";
        if ( session.getAttribute("sysUser") != null) {
            int uid = ((SysUser) session.getAttribute("sysUser")).getUid();
            curriculum.setCreatid(uid);
        }

        String time=Tools.getNowDate();
        curriculum.setCreattime(time);
        int num=curriculumService.add(curriculum);
        if(num>0){
            status="1";
        }else{
            status="0";
        }
        Map<String, Object> map = new HashMap<String, Object>();

        map.put("status",status);
        return map;
    }

    /**
     * 编辑
     * @return
     */
    @RequestMapping(value = "/edit")
    public ModelAndView edit(HttpServletRequest request) {
        ModelAndView modelAndView = new ModelAndView();
        String id=request.getParameter("id");
        String msg="";
        Curriculum curriculum=null;
        if(!"".equals(id)){
            int intId=Integer.parseInt(id);
            curriculum=curriculumService.getById(intId);
        }

        if(curriculum==null){
            msg="获取成功";
        }else{
            msg="获取失败";
        }

        modelAndView.addObject("obj",curriculum);
        modelAndView.setViewName("/sys/learning/curriculum_edit");
        return modelAndView;
    }

    /**
     * 编辑
     * @return
     */
    @RequestMapping(value = "/editData")
    @ResponseBody
    public Map<String,Object> editData(
            @ModelAttribute("curriculum") Curriculum curriculum,
            HttpSession session,
            HttpServletRequest request,
            HttpServletResponse response) {
        String status="";
        int num=curriculumService.edit(curriculum);
        if(num>0){
            status="1";
        }else{
            status="0";
        }
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("status",status);
        return map;
    }


    /**
     *  为人员分配课程
     * @param request
     * @param response
     * @return
     */
    @RequestMapping(value = "/distribute", method = RequestMethod.GET)
    public ModelAndView distribute(
            HttpServletRequest request,
            HttpServletResponse response
    ) {
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.setViewName("/sys/learning/userList");
        return modelAndView;
    }

    @RequestMapping(value = "/distributeQuery")
    @ResponseBody
    public Map<String,Object> distributeQuery(HttpServletRequest req) {
        Map<String, Object> map = new HashMap<String, Object>();
        String pageIndexStr = req.getParameter("pageIndex");
        String passport = req.getParameter("passport");
        String realname = req.getParameter("realname");
        String regtime = req.getParameter("regtime");

        int pageIndex = 1;
        if (pageIndexStr != null && !"".equals(pageIndexStr)) {
            pageIndex = Integer.parseInt(pageIndexStr);
        }

        SysUser sysUser = new SysUser();
        sysUser.setPassport(passport);
        sysUser.setRealname(realname);
        sysUser.setRegtime(regtime);
        Page p = this.sysUserService.getUserList(sysUser, pageSize, pageIndex);

        map.put("pageCount",p.getTotalPageCount() );
        map.put("tableData",p.getResult());
        return map;
    }
    @RequestMapping(value = "/distributePage", method = RequestMethod.GET)
    public ModelAndView distributePage(
            HttpServletRequest request,
            HttpServletResponse response
    ) {
        ModelAndView modelAndView = new ModelAndView();
        String msg = "说明：由于选择了对多人进行课程指定，所以只对每个人员进行课程增加，而不会修改或者删除。";
        String idsStr = request.getParameter("ids");
        List<Curriculum> curriculumList = new ArrayList<Curriculum>();//被选中的课程
        List<SysUser> userList = new ArrayList<SysUser>();
        String userNames = "";
        List<Curriculum> allCurr = this.curriculumService.getAll();//所有的课程
        if(idsStr!=null && !"".equals(idsStr))
        {
            String[] idList = idsStr.split(",");
            if(idList.length> 0)
            {
                //如果只是编辑一个人的课程，则要显示他已经选了哪些课程
                //多个人不需要（也不能显示他们选了哪些课程）
                if(idList.length == 1)
                {
                    msg = "";
                    curriculumList = this.curriculumService.getByUid(Integer.parseInt(idList[0]));
                    if(curriculumList.size() > 0)
                    {
                        for(Curriculum c:curriculumList)
                        {
                            for(Curriculum cc:allCurr)
                            {
                                if(c.getId() == cc.getId())
                                {
                                    cc.setIsSelected(1);//已经被选
                                }
                            }
                        }
                    }
                }
                for (String id:idList)
                {
                    if(Tools.isNumber(id))
                    {
                        SysUser user = this.sysUserService.getUser(Integer.parseInt(id));
                        if(userNames.equals(""))
                        {
                            userNames = userNames + user.getRealname();
                        }
                        else {
                            userNames = userNames +","+ user.getRealname();
                        }

                        userList.add(user);
                    }
                }
            }
        }
//        modelAndView.addObject("currList",curriculumList);
        modelAndView.addObject("allCurr",allCurr);
        modelAndView.addObject("userNames",userNames);
//        modelAndView.addObject("userList",userList);
        modelAndView.addObject("ids",idsStr);
        modelAndView.addObject("msg",msg);
        modelAndView.setViewName("/sys/learning/distributePage");
        return modelAndView;
    }


    @RequestMapping(value = "/distributePageDo")
    @ResponseBody
    public Map<String,Object> distributePageDo(
            HttpSession session,
            HttpServletRequest request,
            HttpServletResponse response) {
        String status="0";
        String idsStr = request.getParameter("ids");
        String[] currIds = request.getParameterValues("currId");
        List<Curriculum> curriculumList = null;//被选中的课程

        if(idsStr!=null && !"".equals(idsStr))
        {
            if(currIds != null && currIds.length > 0)
            {
                ArrayList<Integer> currIdList = new ArrayList<Integer>();
                for(String id:currIds)
                {
                    if(Tools.isNumber(id))
                    {
                        currIdList.add(Integer.parseInt(id));
                    }
                }
                curriculumList = this.curriculumService.getByIds(currIdList);
            }
            String[] idList = idsStr.split(",");
            if (idList.length > 0)
            {
                //如果只是针对一个人的，则需要将没有选中的置为无效
                if(idList.length == 1)
                {
                    Integer uid = Integer.parseInt(idList[0]);
                    this.user2curriculumService.update(uid,curriculumList);//更新个人课程
                }
                //如果只是针对多个人的，只是新增，而不删除
                else{
                    for(String id: idList)
                    {
                        for(Curriculum c: curriculumList)
                        {
                            this.user2curriculumService.add(Integer.parseInt(id),c);
                        }
                    }
                }
                status = "1";
            }
        }
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("status",status);
        return map;
    }

    @RequestMapping(value = "/getUserCurr")
    @ResponseBody
    public Map<String,Object> getUserCurr(
            HttpSession session,
            HttpServletRequest request,
            HttpServletResponse response) {
        List<Curriculum> list = new ArrayList<Curriculum>();
        String uid = request.getParameter("uid");
        if(uid != null && !"".equals(uid) && Tools.isNumber(uid))
        {
            list = this.curriculumService.getByUid(Integer.parseInt(uid));
        }
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("list",list);
        return map;
    }

}
